/***
 * @Author: 码上talk|RC
 * @Date: 2020-06-09 23:20:41
 * @LastEditTime: 2021-10-10 20:57:43
 * @LastEditors: 码上talk|RC
 * @Description: 
 * @FilePath: /tacomall-api/api/ma/src/main/java/store/tacomall/apima/service/impl/MemberServiceImpl.java
 * @Just do what I think it is right
 */
package store.tacomall.apima.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;

import store.tacomall.apima.service.MemberService;
import store.tacomall.common.entity.member.Member;
import store.tacomall.common.json.ResponseJson;
import store.tacomall.common.mapper.member.MemberMapper;
import store.tacomall.common.util.JwtUtil;
import store.tacomall.common.util.PasswordUtil;
import store.tacomall.common.util.RequestUtil;

@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

  private final Logger logger = LoggerFactory.getLogger(this.getClass());

  @Autowired
  TransactionDefinition transactionDefinition;

  @Autowired
  DataSourceTransactionManager dataSourceTransactionManager;

  @Override
  public ResponseJson<String> loginByMobile(String mobile, String passwd) throws Exception {
    ResponseJson<String> responseJson = new ResponseJson<>();
    String token = "";
    Member member = baseMapper.selectOne(new QueryWrapper<Member>().lambda().eq(Member::getMobile, mobile)
        .eq(Member::getPasswd, PasswordUtil.encode(passwd)));
    if (ObjectUtil.isNull(member)) {
      responseJson.setMessage("账号或密码错误");
      return responseJson;
    }
    Map<String, String> claims = new HashMap<>(1);
    claims.put("id", NumberUtil.toStr(member.getId()));
    JwtUtil jwtUtil = new JwtUtil();
    jwtUtil.setISSUER("api-ma");
    token = jwtUtil.create(claims);
    responseJson.setData(token);
    responseJson.ok();
    return responseJson;
  }

  @Override
  public ResponseJson<Member> info(JSONObject json) {
    ResponseJson<Member> responseJson = new ResponseJson<>();
    responseJson.setData(baseMapper
        .selectOne(new QueryWrapper<Member>().lambda().eq(Member::getId, RequestUtil.getLoginUser().getString("id"))));
    responseJson.ok();
    return responseJson;
  }

}
